Skip to content

POSTGRESQL-INSERT-INTO SELECT

sql
create table table1(    
    id bigint not null        constraint table1_pk            primary key,    
    name varchar(30)
    );
create table table1(    
    id bigint not null        constraint table1_pk            primary key,    
    name varchar(30)
    );

不同于oracel,pg允许不添加 from

sql
insert into db.table1 (id, name)  
select 1, 'anne'
insert into db.table1 (id, name)  
select 1, 'anne'

普遍用法是批量导入,举例如下:

sql
create table db.table_origin  
(  
    id   bigint not null  
        constraint table_origin_pk  
            primary key,  
    name varchar(30)  
);  
  
insert into db.table_origin (id, name)  
select 2, '大明'  
on conflict do nothing;  
  
insert into db.table_origin (id, name)  
select 3, '大白'  
on conflict do nothing;  
  
insert into db.table_origin (id, name)  
select 4, '小黑'  
on conflict do nothing;  
  
  
insert into db.table1 (id, name)  
select (SELECT coalesce(max(id), 0) FROM db.table1) + row_number() over ()  
     , "name"  
from db.table_origin;
create table db.table_origin  
(  
    id   bigint not null  
        constraint table_origin_pk  
            primary key,  
    name varchar(30)  
);  
  
insert into db.table_origin (id, name)  
select 2, '大明'  
on conflict do nothing;  
  
insert into db.table_origin (id, name)  
select 3, '大白'  
on conflict do nothing;  
  
insert into db.table_origin (id, name)  
select 4, '小黑'  
on conflict do nothing;  
  
  
insert into db.table1 (id, name)  
select (SELECT coalesce(max(id), 0) FROM db.table1) + row_number() over ()  
     , "name"  
from db.table_origin;